#include <algorithm>
#include <vector>
using namespace std;

class Solution
{
public:
    static vector<vector<int>> threeSum(vector<int>& nums)
    {
        sort(nums.begin(), nums.end());
        vector<vector<int>> vv;
        int cur = 0;
        int n = nums.size()-1;
        int sum = 0;

        while(cur <= n-2)
        {
            if(nums[cur] > 0)
                break;
            int left = cur + 1;
            int right = n;

            while(left < right)
            {
                sum = nums[left] + nums[right];
                if(sum == -1*nums[cur])
                {
                    vv.push_back({nums[cur], nums[left], nums[right]});
                    left++;
                    right--;
                    //加减完以后不符合条件就别整了
                    while(left < right && nums[left] == nums[left-1])
                    {
                        left++;
                    }
                    while(left < right && nums[right] == nums[right+1])
                    {
                        right--;
                    }
                }
                else if(sum > -1*nums[cur])
                {
                    right--;
                }
                else
                {
                    left++;
                }
            }
            cur++;
            //加完以后可能会不符合条件
            while(cur <= n-2 && nums[cur] == nums[cur-1])
            {
                cur++;
            }
        }
        return vv;
    }
};